#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>


void printResult(MYSQL *mysql);

int main(){
    MYSQL * sql;
    int res;
    sql = mysql_init(NULL);
    printf("MySQL client version : %d \n",mysql_get_client_version());
    if(!mysql_real_connect(sql,"localhost","root","","tcmu",0,NULL,0)){
        puts("Error connecting");
        printf("%s\n",mysql_error(sql));
    }
    else
    {
        puts("Success connecting\n");
        res =  mysql_query(sql, "select * from kv");
        if (res)
	    {
	        printf("query error\n");
        }
        else
        {
           printf("Select * from kv\n");
           printResult(sql);
        }
    }
    return 0;
}

void printResult(MYSQL *mysqlPrint)
{
    printf("Start to print result.\n");
    MYSQL_RES * result;
    int numFields = 0;
    int numRows = 0;
    MYSQL_FIELD * field;
    MYSQL_ROW row;
    int i = 0;
    printf("Start to store result\n");
    result = mysql_store_result(mysqlPrint);
    printf("Start to get the amount of fields and rows!");
    numFields = mysql_num_fields(result);
    numRows = mysql_num_rows(result);
    printf("Fields : %d\n", numFields);
    printf("Rows : %d\n", numRows);
    while(field = mysql_fetch_field(result))
    {
        printf("%s\t", field->name);
    }
    printf("\n");
    if(result)
    {
        while(row = mysql_fetch_row(result))
        {
            for(i = 0; i < numFields; i++)
            {
                printf("%s\t", row[i]);
            }
            printf("\n");
        }
    }
    mysql_free_result(result);
}
